import { createConsumer } from './hub'
import { BUS_EVENTS } from '../constants/busEvents'

const PRESENCE_INTERVAL = 20000

class BaseActionCableConnector {
  constructor (app, authToken, websocketURL = '/signalr-hubs/chat') {
    this.consumer = createConsumer(websocketURL, authToken)
    this.app = app
    this.events = {}
    this.isAValidEvent = () => true

    this.consumer.on('receiveMessage', this.onReceived)

    this.consumer.on('connected', (connectionId) => {
      console.log(connectionId)
    })

    setInterval(() => {
      const getqys = new URLSearchParams(`?${websocketURL.split('?')[1]}`)
      const type = getqys.get('type')
      this.consumer.invoke('updatePresenceAsync', {
        type: type
      })
    }, PRESENCE_INTERVAL)
  }

  disconnect () {
    this.consumer.disconnect()
  }

  // eslint-disable-next-line class-methods-use-this
  onDisconnected () {
    window.bus.$emit(BUS_EVENTS.WEBSOCKET_DISCONNECT)
  }

  onReceived = ({ event, data } = {}) => {
    console.log(data)
    if (this.isAValidEvent(data)) {
      if (this.events[event] && typeof this.events[event] === 'function') {
        this.events[event](data)
      }
    }
  }
}

export default BaseActionCableConnector
